<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 实现页面的基本布局 -->
      <el-card class="tree-card">
        <TreeTool :data="company">
          <el-dropdown-item>添加子部门</el-dropdown-item>
        </TreeTool>
        <!--放置一个属性   这里的props和我们之前学习的父传子 的props没关系-->
        <el-tree
          v-loading="isLoading"
          :data="list"
          :props="{ label: 'name' }"
          default-expand-all
        >
          <template v-slot="{ data }">
            <tree-tool :data="data">
              <!-- 下拉选项 -->
              <el-dropdown-item
                v-if="$store.getters.points.includes('add-dept')"
                @click.native="onAdd(data)"
              >添加子部门</el-dropdown-item>
              <el-dropdown-item
                @click.native="onEdit(data)"
              >编辑部门</el-dropdown-item>
              <el-dropdown-item
                @click.native="onDel(data.id)"
              >删除部门</el-dropdown-item>
            </tree-tool>
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 新增部门弹窗 -->
    <add-dept
      ref="addDeptRef"
      :visible.sync="showDialog"
      :node="currentNode"
      @success="getList()"
    ></add-dept>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import TreeTool from './components/tree-tool.vue'
import { delDept, getDeptById, getList } from '@/api/departments.js'
import { translateListToTree } from '@/utils/index.js'
import AddDept from './components/add-dept.vue'

export default {
  name: 'Departments',
  components: {
    TreeTool,
    AddDept
  },
  props: {},
  data() {
    return {
      isLoading: false,
      showDialog: false, // 控制对话显示
      currentNode: {},
      company: { name: '', manager: '负责人' },
      list: []
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.isLoading = true
      const { companyName, depts } = await getList()
      this.company.name = companyName
      this.list = translateListToTree(depts, '')
      this.isLoading = false
    },
    onAdd(node) {
      console.log('添加')
      this.showDialog = true
      this.currentNode = node
    },
    async onEdit(node) {
      console.log('编辑')
      this.currentNode = node
      this.$refs.addDeptRef.form = await getDeptById(node.id)
      this.showDialog = true
    },
    onDel(id) {
      console.log('删除', id)
      // 确认删除
      // 通过elmecon
      this.$confirm('确认删除?', '提示', {
        confimButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        debugger
        // 发请求
        await delDept(id)
        // 提示成功
        this.$mesage.success('操作成功')
        // 刷新
        this.getList()
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
.el-dropdown-link {
  margin-left: 10px;
}
</style>
